﻿using System;
using System.IO.Ports;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace WorkGps
{
    public class GPS
    {
        private SerialPort port = null;
        //private Timer timer = null;

        public GPSData Data { get; private set; }

        public GPS (SerialPort port)
        {
            this.port = port;
            this.port.DataReceived += PortDataReceived;
            Data = null;
        }

        public void StartRead ()
        {
            try
            {
                port.Open();
                while (true)
                {
                    
                }

            }
            catch (Exception)
            {
                throw new Exception(string.Format("Неможливо відкрити порт : {0}", port.PortName));
            }
        }

        public void EndRead (object sender)
        {
            lock (this)
            {
                if (port.IsOpen)
                    port.Close();
                //timer.Dispose();
            }
        }

        void PortDataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            lock (this)
            {
                if (port.IsOpen)
                    Data = ParceData(port.ReadLine());
            }
            if (Data != null)
            {
                EndRead(null);
            }
        }
        
        private GPSData ParceData (string str)
        {
            IGPSParcer gpsParcer = null;
            string[] data = str.Split(',');
            switch (data[0])
            {
                case "$GPGGA":
                    {
                        gpsParcer = new GGAGPSParcer();
                        break;
                    }
                case "$GPRMC":
                    {
                        gpsParcer = new RMCGPSParcer();
                        break;
                    }
            }
            return gpsParcer != null ? gpsParcer.Parce(data) : null;
        }
    }
}
